<!DOCTYPE html>
<html>
<head>
	<title>Canvas</title>
</head>
<body>
	<canvas id="canvas" width=400 height=400></canvas>
	<script src="http://code.jquery.com/jquery-2.1.0.js"></script><!--要记得加载jQuery-->
	<script type="text/javascript">
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d");
	ctx.fillStyle="purple";
	ctx.strokeStyle="purple";
	ctx.lineWidth=2;
	var mywidth=canvas.width;
	var myheight=canvas.height;
	var newspeed=5;
	function drawCircle(x,y,radius,ifFill)
	{
		ctx.beginPath();
		ctx.arc(x,y,radius,0,Math.PI*2,false);
		if(ifFill===true)
			ctx.fill();
		else
			ctx.stroke();
	}
	var Ball = function(){
		this.x=10;
		this.y=10;
		this.speedX=5;
		this.speedY=0;
	}
	Ball.prototype.draw=function(){
		ctx.clearRect(0,0,mywidth,myheight);
		drawCircle(this.x,this.y,10,true);
	}
	Ball.prototype.move=function(){
		this.x=this.x+this.speedX;
		this.y=this.y+this.speedY;
		if(this.x<10||this.x>mywidth-10)
			//this.x=mywidth;
		this.speedX = -this.speedX;
			//this.x=0;
		if(this.y<10||this.y>myheight-10)
			this.speedY = -this.speedY;
	}
	Ball.prototype.setDirection=function(direction,newspeed){
		if(direction==="up")
		{
				this.speedY=-newspeed;
				this.speedX=0;//必须对X和Y方向的速度都有设置。
		}
		else if(direction==="down")
		{
				this.speedY=newspeed;
				this.speedX=0;
		}
		else if(direction==="left")
		{
				this.speedX=-newspeed;
				this.speedY=0;
		}
		else if(direction==="right")
		{
				this.speedX=newspeed;
				this.speedY=0;
		}
		else if(direction==="stop")
		{
			this.speedX=0;
			this.speedY=0;
		}
	}
	Ball.prototype.setSpeed = function(speed){
		if(this.speedY<0)
			this.speedY=-speed;
		else if(this.speedY>0)
			this.speedY=speed;
		if(this.speedX<0)
			this.speedX=-speed;
		else if(this.speedX>0)
			this.speedX=speed;
	}
	var keyActions={
		32:"stop",
		37:"left",
		38:"up",
		39:"right",
		40:"down"
	};
	var keySpeed={
		49:1,
		50:2,
		51:3,
		52:4,
		53:5,
		54:6,
		55:7,
		56:8,
		57:9
	};
	var ball = new Ball();

	function animation(){
		ball.draw();
		ball.move();
		ctx.strokeRect(0,0,mywidth,myheight);
	}
	function keydownHandler(event){
		if(event.keyCode<=40){
			var direction=keyActions[event.keyCode];
		ball.setDirection(direction,newspeed);
		}
		else {
			newspeed=keySpeed[event.keyCode];
			ball.setSpeed(newspeed);
		}
	}
	$("body").keydown(keydownHandler);
	setInterval(animation,30);
	</script>
</body>
</html>